package com.songcha.module_bookreader.ui.fragment.slide

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.songcha.module_bookreader.R
import com.songcha.module_bookreader.databinding.BookreaderFragmentSlideBinding
import com.songcha.module_bookreader.event.ChapterSelectedEvent
import com.songcha.module_bookreader.helper.BookDownloadHelper
import com.songcha.module_bookreader.ui.adapter.BookSlideCatalogAdapter
import com.songcha.library_base.mvvm.base.BaseMvvmFragment
import com.songcha.library_business.bean.book.BookChapterCatalogBean
import com.songcha.library_business.config.FunctionConfig
import com.songcha.library_business.enums.BookDownloadStatus
import com.songcha.library_business.event.book.BookDownloadCompleteEvent
import com.songcha.library_business.event.book.BookDownloadErrorEvent
import com.songcha.library_business.event.book.BookDownloadingEvent
import com.songcha.library_business.event.book.InBookShelfEvent
import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.util.ColorUtil

import com.songcha.library_common.util.GlideUtil
import com.songcha.library_common.util.StringUtil
import com.songcha.library_common.util.ToastUtil
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe

class BookReadSlideFragment:BaseMvvmFragment<BookReadSlideViewModel,BookreaderFragmentSlideBinding>(),com.chad.library.adapter.base.listener.OnItemClickListener,View.OnClickListener {
    private var mAdapter: BookSlideCatalogAdapter?=null
    //private var mList= mutableListOf("1","2","3","4","5")
    private var mCloseListener:(()->Unit)?=null

    override fun getLayoutId(): Int {
        return R.layout.bookreader_fragment_slide
    }

    fun switchMode(isDark:Boolean,bgIdx:Int){
        if(!isViewModelInitialized()) return
        viewModel.isDark=isDark
        viewModel.bgIdx=bgIdx
        initMode(isDark,bgIdx)
    }

/*    fun setIsInBookShelf(isIn:Boolean){
        if(!isViewModelInitialized()) return
        viewModel.setIsInBookShelf(isIn)
    }*/

    fun setCloseListener(listener:()->Unit){
        mCloseListener=listener
    }

    private fun initMode(isDark: Boolean,bgIdx:Int){
        if(viewModel.isDark){
            databinding.bookreaderSlideLlParent.setContainerBackgroundColor(Color.BLACK)
            databinding.bookreaderTvBookname.setTextColor(Color.WHITE)
            databinding.bookreaderTvAuthor.setTextColor(Color.WHITE)
            databinding.bookreaderTvTextCount.setTextColor(Color.WHITE)
            databinding.bookreaderIvAuthor.setImageResource(com.songcha.library_business.R.mipmap.business_icon_author_white)
        }else{
            when(bgIdx){
                1->{
                    databinding.bookreaderSlideLlParent.setContainerBackgroundColor(ColorUtil.getResourceColor(requireContext(),R.color.read_background_color1))
                }
                2->{
                    databinding.bookreaderSlideLlParent.setContainerBackgroundColor(ColorUtil.getResourceColor(requireContext(),R.color.read_background_color2))
                }
                3->{
                    databinding.bookreaderSlideLlParent.setContainerBackgroundColor(ColorUtil.getResourceColor(requireContext(),R.color.read_background_color3))
                }
                4->{
                    databinding.bookreaderSlideLlParent.setContainerBackgroundColor(ColorUtil.getResourceColor(requireContext(),R.color.read_background_color4))
                }
            }

            databinding.bookreaderTvBookname.setTextColor(Color.BLACK)
            databinding.bookreaderTvAuthor.setTextColor(Color.BLACK)
            databinding.bookreaderTvTextCount.setTextColor(Color.BLACK)
            databinding.bookreaderIvAuthor.setImageResource(com.songcha.library_business.R.mipmap.business_icon_author)
        }
        mAdapter?.switchMode(isDark)
    }

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)

        arguments?.let {
            viewModel.book=it.getParcelable("book")?:return
            viewModel.isDark=it.getBoolean("is_dark",false)
            viewModel.bgIdx=it.getInt("bg_idx",1)
            val list=it.getParcelableArrayList<BookChapterCatalogBean.DataBean>("chapters")?:return
            for (item in list){
                viewModel.chapterList.add(item)
            }
        }

        if(viewModel.chapterList.size==0) return

        viewModel.getIsInBookShelf()

        viewModel.getHasBookAllDownload()

        viewModel.isInBookShelf.observe(this){data->
            if(data){
                databinding.bookreaderTvAddToShelf.text="已加入书架"
            }else{
                databinding.bookreaderTvAddToShelf.text="加入书架"
            }
        }

        initBookInfo()

        initRcv()

        databinding.bookreaderIvOrder.setOnClickListener(this)
        databinding.bookreaderCclDownloadBook.setOnClickListener(this)
        databinding.bookreaderCclAddtoShelf.setOnClickListener(this)
        databinding.bookreaderSlideLlParent.setOnClickListener(this)
        databinding.bookreaderIvClose.setOnClickListener(this)

        initMode(viewModel.isDark,viewModel.bgIdx)

        if(FunctionConfig.IS_VIP_ENABLED){
            if(UserInfoManager.isVip()){
                databinding.bookreaderCclDownloadBook.visibility=View.VISIBLE
            }else{
                databinding.bookreaderCclDownloadBook.visibility=View.GONE
            }
            viewModel.isBookAllDownload.observe(this){data->
                if(data){
                    databinding.bookreaderTvDownloadBook.text="已缓存全本"
                }else{
                    databinding.bookreaderTvDownloadBook.text="缓存全本"
                }
            }

            viewModel.bookDownloadStatus.observe(this){data->
                if(data==BookDownloadStatus.DOWNLOADING){
                    databinding.bookreaderTvDownloadBook.text="缓存中"
                }else if(data==BookDownloadStatus.DOWNLOADED){
                    databinding.bookreaderTvDownloadBook.text="已缓存全本"
                }else{

                }
            }

        }else{
            databinding.bookreaderCclDownloadBook.visibility=View.GONE
        }

        EventBus.getDefault().register(this)

    }

    private fun initBookInfo(){
        GlideUtil.loadNetImage(databinding.bookreaderIvThumb,viewModel.book.thumb)
        databinding.bookreaderTvBookname.text=viewModel.book.bookName
        databinding.bookreaderTvAuthor.text=viewModel.book.author
        databinding.bookreaderTvTextCount.text="${StringUtil.float2PlainString(viewModel.book.textCount/10000f)}万字"
    }

    private fun initRcv(){
        databinding.bookreaderDrawerRcv.apply{
            layoutManager= LinearLayoutManager(context)
            mAdapter=BookSlideCatalogAdapter(viewModel.chapterList,viewModel.isDark)
            mAdapter!!.setOnItemClickListener(this@BookReadSlideFragment)
            adapter=mAdapter
        }
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        var chapter=position+1
        if(viewModel.isReverse){
            chapter=viewModel.chapterList.size-position
        }
        EventBus.getDefault().post(ChapterSelectedEvent(chapter))
    }

    override fun onClick(v: View?) {
        if(v==null) return
        when(v.id){
            R.id.bookreader_iv_order->{
                viewModel.isReverse=!viewModel.isReverse
                viewModel.chapterList.reverse()
                mAdapter?.notifyDataSetChanged()
                databinding.bookreaderDrawerRcv.scrollToPosition(0)
            }
            R.id.bookreader_ccl_download_book->{
                if(viewModel.isBookAllDownload.value==null || viewModel.isBookAllDownload.value!!) return
                //下载的同时加入书架
                if(viewModel.bookDownloadStatus.value!! != BookDownloadStatus.NO_DOWNLOAD) return
                viewModel.addBookToShelf()
                BookDownloadHelper.startBookDownloadService(viewModel.book,viewModel.chapterList)
            }
            R.id.bookreader_ccl_addto_shelf->{
                if(viewModel.isInBookShelf.value!!) return
                viewModel.addBookToShelf()
                ToastUtil.show("已加入书架")
            }
            R.id.bookreader_iv_close->{
                mCloseListener?.let {
                    it()
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe
    fun onInBookShelfEvent(event:InBookShelfEvent){
        if(event.bookId==viewModel.book.id){
            viewModel.isInBookShelf.value=event.isInBookShelf
        }
    }

    @Subscribe
    fun onBookDownloadingEvent(event:BookDownloadingEvent){
        if(event.book.id==viewModel.book.id){
            viewModel.bookDownloadStatus.value=BookDownloadStatus.DOWNLOADING
        }
    }


    @Subscribe
    fun onBookDownloadCompleteEvent(event:BookDownloadCompleteEvent){
        if(event.book.id==viewModel.book.id){
            viewModel.bookDownloadStatus.value=BookDownloadStatus.DOWNLOADED
        }
    }

    @Subscribe
    fun onBookDownloadErrorEvent(event:BookDownloadErrorEvent){

    }

}